package main

import (
	"context"
	"fmt"

	"github.com/project-flogo/contrib/activity/log"
	"github.com/project-flogo/core/activity"
	"github.com/project-flogo/core/api"
	"github.com/project-flogo/core/data/coerce"
	"github.com/project-flogo/core/data/metadata"
	"github.com/project-flogo/core/engine"

	dt "gitee.com/shipnet/flogo_metric_data_trigger"
)

func main() {

	app := myApp()

	e, err := api.NewEngine(app)

	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	engine.RunEngine(e)
}

func myApp() *api.App {
	app := api.NewApp()

	settings := &dt.Settings{
		Addr: "192.168.1.17:6379",
		DB:   1,
		Sub:  "network.isConnected",
	}
	trg := app.NewTrigger(&dt.Trigger{}, settings)
	h, _ := trg.NewHandler(&dt.HandlerSettings{})
	h.NewAction(RunActivities)

	//store in map to avoid activity instance recreation
	act, err := api.NewActivity(&log.Activity{}, map[string]interface{}{})
	if err != nil {
		return app
	}
	activities = map[string]activity.Activity{"log": act}

	return app
}

var activities map[string]activity.Activity

func RunActivities(ctx context.Context, inputs map[string]interface{}) (map[string]interface{}, error) {

	trgOut := &dt.Output{}
	trgOut.FromMap(inputs)

	// msg, _ := coerce.ToString(trgOut.AnOutput)
	fmt.Printf("trgOut: %+v\n", trgOut.Data)
	m, err := coerce.ToObject(trgOut.Data)
	if err != nil {
		return nil, err
	}
	input := &log.Input{}
	err = metadata.MapToStruct(m, input, true)
	if err != nil {
		return nil, err
	}
	_, err = api.EvalActivity(activities["log"], input)
	if err != nil {
		return nil, err
	}

	return map[string]interface{}{}, nil
}
